var fs = require("fs");
var path = require("path");
var config = require('../../config.json');
var local_repos = config.local_repo_addr;
var LocalRepoProxy = require('../../proxy/local_repo.js');
var logger = require('log4js').getLogger();
var uuid = require('uuid');
var zip = require('../../common/zip.js');
var EventProxy = require('eventproxy');
var decompress = require('decompress');
var decompressUnzip = require('decompress-unzip');
var removeDir = require('../../common/removeDir.js');
var sdp_agent = config.server_agent.host + ":" + config.server_agent.port;
var messageAgent = require("../../common/message.js");
var request = require('request');

/**
 * 下载商品
 * POST请求
 * @param：{fileName:"",version:"",other_info:"",type:""}
 */

exports.download = function (req, res, next) {
    var task_id = uuid.v1();
    res.format_json({task_id: task_id}, 200);
    messageAgent.setMessage(task_id, {msg: "开始下载", isCompleted: false, err: null});
    request.post(sdp_agent + '/local_repo/download', {form: req.body}, function (err, response, data) {
        var dataJson = JSON.parse(data);
        var agent_task = dataJson.data.task_id;
        messageAgent.getMessage(sdp_agent + '/message/' + agent_task, function (msg) {
            if (msg.err) {
                messageAgent.setMessage(task_id, {msg: null, isCompleted: true, err: msg.err});
            } else {
                if (msg.isCompleted) {
                    LocalRepoProxy.addLocalRepo({
                        fileName: req.body.fileName,
                        version: req.body.version,
                        other_info: req.body.other_info
                    }, function (err, data) {
                        if (err) {
                            messageAgent.setMessage(task_id, {msg: null, isCompleted: true, err: err});
                            return false;
                        }
                        messageAgent.setMessage(task_id, {msg: msg.msg, isCompleted: true, err: null});
                    });

                }

            }
        });

    });
};

/**
 * 更新本地仓库文件和数据库版本信息
 * PUT请求
 * @param：{fileName:"",version:""}
 */

exports.update = function (req, res, next) {
    var task_id = uuid.v1();
    res.format_json({task_id: task_id}, 200);
    messageAgent.setMessage(task_id, {msg: "开始更新", isCompleted: false, err: null});
    //setTimeout(function () {  //不靠谱
    var fileName = req.body.fileName;
    var version = req.body.version;
    var type = req.body.type;
    LocalRepoProxy.getLocalRepoByFileName(fileName,
        function (err, data) {
            if (err) {
                messageAgent.setMessage(task_id, {msg: null, isCompleted: true, err: "从本地仓库获取依赖信息失败"});
                logger.error("从本地仓库获取依赖信息失败：" + err);
            } else {
                if (data) {
                    if (data.version == version) {  //本地仓库中有目标版本
                        LocalRepoProxy.updateLocalRepo(
                            fileName, version, function (err, data) {
                                if (err) {
                                    messageAgent.setMessage(task_id, {msg: null, isCompleted: true, err: "依赖更新失败"});
                                    logger.error("依赖更新失败：" + err);
                                } else {
                                    messageAgent.setMessage(task_id, {msg: "依赖更新成功", isCompleted: true, err: null});
                                    logger.info("依赖更新成功");
                                }
                            });
                    } else {
                        request.post(sdp_agent + '/local_repo/update', {form: req.body}, function (err, response, data) {
                            var dataJson = JSON.parse(data);
                            if (dataJson.code == 200) {
                                if (dataJson.data.task_id) {
                                    messageAgent.getMessage(sdp_agent + '/message/' + dataJson.data.task_id, function (msg) {
                                        if (msg.err) {
                                            logger.error(msg.err);
                                            messageAgent.setMessage(task_id, {
                                                msg: null,
                                                isCompleted: true,
                                                err: "依赖更新失败"
                                            });
                                            return false;
                                        } else {
                                            if (msg.isCompleted) {
                                                LocalRepoProxy.updateLocalRepo(fileName, version, function (err, data) {
                                                    if (err) {
                                                        messageAgent.setMessage(task_id, {
                                                            msg: null,
                                                            isCompleted: true,
                                                            err: "依赖更新失败"
                                                        });
                                                        return false;
                                                    } else {
                                                        messageAgent.setMessage(task_id, {
                                                            msg: "依赖更新成功",
                                                            isCompleted: true,
                                                            err: null
                                                        });
                                                        logger.info("依赖更新成功")
                                                    }
                                                });

                                            }
                                        }
                                    })
                                }
                            }
                        });
                    }
                } else {
                    messageAgent.setMessage(task_id, {msg: null, isCompleted: true, err: "从本地仓库获取依赖信息失败"});
                    logger.error("从本地仓库获取依赖信息失败：" + err);
                }
            }
        }
    );
    //}, 200);
};


var CountDown = function (count, callback) {
    this.down = function () {
        if (!--count) callback(null, {
            successNum: successNum,
            errs: errs
        });
    }
    var successNum = 0;
    this.addSuccessNum = function () {
        successNum++;
    }
    var errs = [];
    this.addErrs = function (err) {
        errs.push(err);
    }
}

/**
 * 复制本地仓库文件到工作空间
 * @param：{tar_fullPath:"",fileNames:[]}
 * tar_fullPath 为全路径 fileNames数组中的文件名字一定要包含后缀名
 */
exports.copy = function (req, res, next) {
    var tar_fullPath = req.body.tar_fullPath;
    var fileNames = req.body["fileNames[]"];
    if (null != tar_fullPath && null != fileNames && fileNames.length > 0) {
        var countDown = new CountDown(fileNames.length, function (err, data) {
            res.json({
                data: data
            });
        });
        for (var i = 0; i < fileNames.length; i++) {
            copyFile({
                tar_fullPath: tar_fullPath,
                fileName: fileNames[i]
            }, function (err, data) {
                if (err) {
                    countDown.addErrs(err);
                } else {
                    countDown.addSuccessNum();
                }
                countDown.down();
            });
        }
    } else {
        res.json({
            data: false,
            err: "参数不全，无法拷贝"
        });
    }
}


/**
 * 复制本地仓库文件到工作空间
 * @param：{tar_fullPath:"",fileNames:[]}
 * tar_fullPath 为全路径 fileNames数组中的文件名字一定要包含后缀名
 */
exports.copyList = function (tar_fullPath, fileNames, call_back) {
    if (null != tar_fullPath && null != fileNames && fileNames.length > 0) {
        var countDown = new CountDown(fileNames.length, function (err, data) {
            exe_callback(err, data, call_back);
        });
        for (var i = 0; i < fileNames.length; i++) {
            copyFile({
                tar_fullPath: tar_fullPath,
                fileName: fileNames[i]
            }, function (err, data) {
                if (err) {
                    countDown.addErrs(err);
                } else {
                    countDown.addSuccessNum();
                }
                countDown.down();
            });
        }
    } else {
        exe_callback("参数不全，无法拷贝", null, call_back);
    }
}


/**
 *
 * 获取本地仓库
 */
exports.getLocalRepo = function (req, res, next) {
    LocalRepoProxy.getLocalRepo(function (err, data) {
        if (err) {
            return res.format_json(null, 500, err);
        }
        res.format_json(data, 0);
    });

}

exports.getFileInfoByName = function (req, res, next) {
    var fileName = req.params.file_name;
    LocalRepoProxy.getLocalRepoByFileName(fileName, function (err, data) {
        if (err) {
            return res.format_json(null, 500, err);
        }
        res.format_json(data, 0);
    })
}


/**
 *将本地仓库文件拷贝到其它位置
 */
function copyFile(param, callback) {
    if (null == param.fileName || param.fileName.trim().length == 0) {
        exe_callback("参数fileName为空，拷贝失败", null, callback);
    } else if (null == param.tar_fullPath || param.tar_fullPath.trim().length == 0) {
        exe_callback("参数tar_fullPath为空，拷贝失败", null, callback);
    } else {
        var fullFileName = path.join(local_repos, param.fileName);
        // var emitter = new events.EventEmitter();
        fs.exists(fullFileName, function (exists) {
            if (exists) {
                fs.lstat(param.tar_fullPath, function (err, stat) {
                    if (stat.isDirectory()) {
                        param.tar_fullPath = path.join(param.tar_fullPath, param.fileName);
                    }
                    var readStream = fs.createReadStream(fullFileName);
                    var writeStream = fs.createWriteStream(param.tar_fullPath);
                    writeStream.on('err', function (err, data) {
                        readStream.pause();
                        exe_callback(err, data, callback);
                    });
                    readStream.on('err', function (err, data) {
                        readStream.pause();
                        exe_callback(err, data, callback);
                    });
                    readStream.pipe(writeStream).on('finish', function () {
                        exe_callback(null, null, callback);
                    });
                });
            } else {
                exe_callback("文件" + fullFileName + "不存在,拷贝失败", null, callback);
            }
        });
    }
};

/**
 *删除本地仓库文件
 *param = {fileName:""}
 */
exports.deleteFile = function (param, callback) {
    if (null == param.fileName || param.fileName.trim().length == 0) {
        exe_callback(null, "参数fileName为空，无法执行删除", callback);
    } else {
        fs.exists(path.join(local_repos, param.fileName), function (exists) {
            if (exists) { //执行删除
                fs.unlink(path.join(local_repos, param.fileName), function (err, data) {
                    exe_callback(err, data, callback);
                })
            } else {
                exe_callback(null, "文件已经不存在，无需删除", callback);
            }
        });
    }
};


/**
 *执行callback
 */
function exe_callback(err, data, callback) {
    if (callback && typeof callback === 'function') {
        callback(err, data);
    }
}

